<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Middleware\Auth;

use App\Exception\NoPermissionException;
use App\Traits\ResponseTrait;
use Exception;
use Hyperf\Di\Annotation\Inject;
use HyperfExtension\Jwt\Contracts\ManagerInterface;
use HyperfExtension\Jwt\Exceptions\TokenExpiredException;
use HyperfExtension\Jwt\JwtFactory;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RefreshTokenMiddleware implements MiddlewareInterface
{
    /**
     * 用于限制jwt token不能跨端使用
     * @var string
     */
    protected $guard = "admin";

    use ResponseTrait;

    protected ContainerInterface $container;

    #[Inject]
    private ManagerInterface $manager;

    #[Inject]
    private JwtFactory $jwtFactory;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $jwt = $this->jwtFactory->make();
        try {
//            $user = $jwt->checkOrFail();
            $payload = $jwt->getPayload()->toArray();
            $guard = $payload['guard'] ?? "";
            if ($this->guard !== $guard) {
                throw new NoPermissionException("授权异常");
            }
        } catch (Exception $exception) {
            if (!$exception instanceof TokenExpiredException) {
                return $this->error($exception->getMessage(), 50008);
            }

            try {
                $token = $jwt->getToken();

                // 刷新token
                $new_token = $jwt->getManager()->refresh($token);

                // 解析token载荷信息
                $payload = $jwt->getManager()->decode($token, false, true);

                // 旧token加入黑名单
                $jwt->getManager()->getBlacklist()->add($payload);

                // 一次性登录，保证此次请求畅通
                auth($payload->get('guard') ?? config('auth.default.guard'))->onceUsingId($payload->get('sub'));

                return $handler->handle($request)->withAddedHeader('authorization', 'bearer ' . $new_token);
            } catch (Exception $exception) {
                return $this->error($exception->getMessage(), 50008);
            }
        }

        return $handler->handle($request);
    }
}
